package com.trainfinder.proxy;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public abstract class AbstractRemoteRunnable implements Runnable {

	private final Logger logger;

	private final int uniqueIndex;

	protected AbstractRemoteRunnable(Logger logger, int uniqueIndex) {

		this.logger = logger;
		this.uniqueIndex = uniqueIndex;
	}

	public void run() {

		Service service = getService();

		try {

			final InputStream input = service.getInputStream();
			final OutputStream output = service.getOutputStream();

			synchronized (output) {
				// StringBuffer sb = new StringBuffer();
				try {

					byte[] bytes = new byte[10240];
					int count = 0;
					while (count != -1) {

						// System.out.println("waiting to read bytes..");
						count = input.read(bytes, 0, bytes.length);
						// System.out.println("read "+count+" bytes");

						if (count == -1) {
							output.write(-1);
							output.flush();
							break;
						} else {
							output.write(bytes, 0, count);
							logger.log(PortType.Remote, uniqueIndex, bytes,
									count);
						}

						output.flush();

					}
				} catch (IOException e) {
					e.printStackTrace();
				} finally {
					output.close();
					input.close();
				}
			}
		} catch (IOException e) {
			// e.printStackTrace();
		} catch (ServerCreationException e) {
			// TODO Auto-generated catch block
			// e.printStackTrace();
		}

	}

	protected abstract Service getService();

}
